
package shopping

import (
    "dhfshop/models"
	"strings"
	"errors"
	"github.com/astaxie/beego/orm"
)

//退换货统计
type ReturnReport struct {
	PartnerId     int64     `orm:"column(partner_id);pk;auto" json:"partner_id" form:"partner_id"` //分销商编号 
	CompanyId     int64     `orm:"column(company_id)" json:"company_id" form:"company_id"`    //
	Name          string  `orm:"column(name)" json:"name" form:"name"`              //分销商名称
	RefundCount   int32   `orm:"column(refund_count)" json:"refund_count" form:"refund_count"`  //退款笔数
	RefundAmount  float32 `orm:"column(refund_amount);digits(12);decimals(2)" json:"refund_amount" form:"refund_amount"` /* 退款金额*/
	ReturnCount   int32   `orm:"column(return_count)" json:"return_count" form:"return_count"`  //退货笔数
	ReturnAmount  float32 `orm:"column(return_amount);digits(12);decimals(2)" json:"return_amount" form:"return_amount"` /* 退货金额*/
	ReplaceCount  int32   `orm:"column(replace_count)" json:"replace_count" form:"replace_count"`  //换货笔数
	ReplaceAmount float32 `orm:"column(replace_amount);digits(12);decimals(2)" json:"replace_amount" form:"replace_amount"` /* 换货金额*/
}

func init() {
    orm.RegisterModel(new(ReturnReport))   
}

func AddReturnReport(m *ReturnReport) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetReturnReportById(id int64) (v *ReturnReport, err error) {
	o := models.GetDefaultDB()
	v = &ReturnReport{PartnerId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetAllReturnReports(query map[string]string, fields []string, order_by map[string]string, 
    offset int, limit int) ([]*ReturnReport, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(ReturnReport))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*ReturnReport
	if _, err := qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdateReturnReportById(m *ReturnReport, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := ReturnReport{PartnerId: m.PartnerId}
	if err = o.Read(&v); err != nil {
		return err
	}else{
	    if _, err = o.Update(m, k...); err != nil {
		   return err
		}
	}
	return nil
}

func DeleteReturnReport(id int64) (err error) {
	o := models.GetDefaultDB()
	v := ReturnReport{PartnerId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}
